// TODO: need a test file per header in tuple_utils and include the header first, to detect potentially missing includes

#include "simple/support/tuple_utils.hpp"
#include "simple/support/function_utils.hpp"

#include <cassert>
#include <string>
#include <sstream>
#include <array>


using namespace simple::support;
using namespace std::literals;

struct one_t { static constexpr int value = 1; } one;
struct five_t { static constexpr int value = 5; } five;
struct seventy_seven_t { static constexpr int value = 77; } seventy_seven;

void ApplyFor()
{
	{
		auto t = std::tuple("minus one ", 0," one ",2," three");
		std::stringstream ss;
		apply_for<std::is_arithmetic>(true, [&ss](auto&& a)
		{
			ss << a;
		}, t);
		assert(ss.str() == "0");
	}

	{
		auto t = std::tuple(seventy_seven, five, one);
		auto and_nothing_else = [](auto){ assert(false); };
		apply_for(5,  overload{ [](five_t a)          { assert(a.value == 5); },  and_nothing_else }, t);
		apply_for(77, overload{ [](seventy_seven_t a) { assert(a.value == 77); }, and_nothing_else }, t);
		apply_for(1,  overload{ [](one_t a)           { assert(a.value == 1); },  and_nothing_else }, t);
		assert( apply_for(5, [](auto&& a) { return a.value + 1; }, t) == 6 );
	}
}

void ApplyTo()
{
	auto t = std::tuple(0," one ",2," three");
	std::stringstream ss;

	apply_to({0,4}, [&ss](auto&& a)
	{
		ss << a;
	}, t);
	assert(ss.str() == "0 one 2 three");
	ss.str("");
	ss.clear();

	apply_to({1,3}, [&ss](auto&& a)
	{
		ss << a;
	}, t);
	assert(ss.str() == " one 2");
	ss.str("");
	ss.clear();

	apply_to(3, [&ss](auto&& a)
	{
		ss << a;
	}, t);
	assert(ss.str() == " three");
	ss.str("");
	ss.clear();

	auto t2 = std::tuple(0,1.1,2,3);

	apply_to(2, [](auto&& x)
			{ x += 2; }, t2) ;
	assert( std::tuple(0,1.1,4,3) == t2 );

	apply_to({1, 3}, [](auto&& x)
			{ x += 2; }, t2) ;
	assert( std::tuple(0,3.1,6,3) == t2 );

	auto t3 = std::tuple(0,1,2,3);
	assert( 4 == apply_to(2, [](auto&& x)
			{ return x + 2; }, t3) );

}

template <typename... T>
constexpr auto tuple_tie(std::tuple<T...>& t)
{
	return std::apply(std::tie<T...>, t);
}

template <typename... T>
constexpr auto tuple_tie_for_ubsan(std::tuple<T...>& t)
{
	return std::apply(&std::tie<T...>, t);
}

void CarCdr()
{

	{ auto t = std::tuple(true, 1.5, 5);
		assert(tuple_car(t));
		assert(1.5 == tuple_car(tuple_cdr(t)));
	}

	{ auto t = std::tuple(1, 2, 3);

		// auto tref = std::tuple<int&, int&, int&>(
		// 		std::get<0>(t),
		// 		std::get<1>(t),
		// 		std::get<2>(t));
		// // ubsan: ok

		// auto tref = std::apply([](auto&&... x) { return std::tie(x...); }, t);
		// // ubsan: ok

		// auto tref = tuple_tie_for_ubsan(t);
		// // ubsan: ok

		auto tref = tuple_tie(t);
		// ubsan:
		// tuple_utils.cpp:62:37: runtime error: reference binding to misaligned address 0x00022897 for type '<unknown>', which requires 2 byte alignment
		// /usr/include/c++/7/tuple:1673:21: runtime error: reference binding to misaligned address 0x00022897 for type 'type', which requires 2 byte alignment
		// /usr/include/c++/7/bits/move.h:74:36: runtime error: reference binding to misaligned address 0x00022897 for type '<unknown>', which requires 2 byte alignment
		// /usr/include/c++/7/tuple:1663:51: runtime error: reference binding to misaligned address 0x00022897 for type 'type', which requires 2 byte alignment
		// /usr/include/c++/7/bits/invoke.h:96:36: runtime error: reference binding to misaligned address 0x00022897 for type 'type', which requires 2 byte alignment
		// /usr/include/c++/7/bits/invoke.h:60:31: runtime error: reference binding to misaligned address 0x00022897 for type 'type', which requires 2 byte alignment
		// happens on:
		// Linux localhost 3.0.101-g1a2acd3 #1 SMP PREEMPT Wed Mar 23 04:06:52 PDT 2016 armv7l armv7l armv7l GNU/Linux
		// g++-7 (Ubuntu/Linaro 7.4.0-1ubuntu1~14.04~ppa1) 7.4.0
		// or
		// g++-9 (Ubuntu 9.3.0-11ubuntu0~14.04) 9.3.0


		assert(t == tref);

		tuple_car(tref) = -4;

		assert(tuple_car(t) == -4);
		assert(t == tref);

		auto tref_cdr = tuple_tie_cdr(tref);

		tuple_car(tref_cdr) = 13;

		assert(std::get<1>(t) == 13);
		assert(tref_cdr == std::tuple(13,3));

		auto tref_cdr2 = tuple_tie_cdr(t);
		tuple_car(tref_cdr2) = 12;

		assert(std::get<1>(t) == 12);
		assert(tref_cdr2 == tref_cdr);
		assert(tref_cdr2 == std::tuple(12,3));
		assert(tref_cdr == std::tuple(12,3));

		auto tref_cdr3 = tuple_tie_cdr(tref_cdr2);
		tuple_car(tref_cdr3) = 99;
		assert(std::get<2>(t) == 99);
		assert(tref_cdr3 == std::tuple(99));

		auto tref_cdr4 = tuple_cdr(tref_cdr2);
		tuple_car(tref_cdr4) = 88;
		assert(std::get<2>(t) != 88);
		assert(tref_cdr4 == std::tuple(88));

		using short_int_long_nil = tuple_cdr_t<
			std::tuple<char, short, int, long>>;
		static_assert(std::is_same_v<
			short_int_long_nil, std::tuple<short, int, long>>);
		static_assert(std::is_same_v<
			tuple_car_t<short_int_long_nil>, short>);

		using int_long_nil = tuple_cdr_t<short_int_long_nil>;
		static_assert(std::is_same_v<
			int_long_nil, std::tuple<int, long>>);
		static_assert(std::is_same_v<
			tuple_car_t<int_long_nil>, int>);

		using long_nil = tuple_cdr_t<int_long_nil>;
		static_assert(std::is_same_v<
			long_nil, std::tuple<long>>);
		static_assert(std::is_same_v<
			tuple_car_t<long_nil>, long>);

		using nil = tuple_cdr_t<long_nil>;
		static_assert(std::is_same_v<
			nil, std::tuple<>>);
	}
}

void TransformBasic()
{
	assert
	((
		transform([](auto x) { return x + x; },
			std::tuple{1, "2"s, 3.4})
		== std::tuple{2, "22"s, 6.8}
	));

	assert
	((
		transform(std::plus<>{},
			std::tuple{1, "2"s, 3.4}, std::tuple{4, "3"s, 2.1})
		== std::tuple{5, "23"s, 5.5}
	));

	assert
	((
		transform(std::plus<>{},
			std::array{1, 2, 3}, std::tuple{3, 2, 1})
		== std::tuple{4, 4, 4}
	));

	assert
	((
		transform(std::plus<>(),
			std::tuple{1, 2, 3.3}, std::array{3, 2, 1})
		== std::tuple{4, 4, 4.3}
	));

	assert
	((
		transform(std::plus<>{},
			std::tuple{1, 2, 3.3, 4, 5}, std::array{3, 2, 1})
		== std::tuple{4, 4, 4.3}
	));

	assert
	((
		transform
		(
			[](auto... x) { return (x + ...); },
			std::tuple{"1"s, 2},
			std::tuple{"3"s, 4},
			std::tuple{"5"s, 6}
		)
		== std::tuple{"135"s, 12}
	));

	auto longstr =  "wow am so stateful look at me ~ "s;
	assert
	((
		transform(
			overload
			{
				[state = longstr]
				(auto x) { return state.size() + x; },
				[state = longstr]
				(std::string x) { return state + x;}
			},
			std::tuple{1, "2"s, 3.4})
		== std::tuple
		{
			longstr.size() + 1,
			longstr + "2"s,
			longstr.size() + 3.4
		}
	));

}

struct counter
{
	static size_t inst;
	static size_t copy;
	static size_t move;

	counter() { ++inst; };
	counter(const counter&) {  ++copy; }
	counter(counter&&) {  ++move; }
};
size_t counter::inst = 0;
size_t counter::copy = 0;
size_t counter::move = 0;

void TransformCopyCount()
{

	auto x = transform([](auto&& x) -> decltype(auto) { return std::forward<decltype(x)>(x); },
		std::tuple{counter{}, counter{}, counter{}} );
	assert(3 == get<0>(x).inst);
	assert(0 == get<1>(x).copy);
	assert(6 == get<2>(x).move);
	assert(3 == counter::inst);
	assert(0 == counter::copy);
	assert(6 == counter::move);

}

void TransformReturnVoid()
{

	assert
	((
		transform([](auto...){},
			std::tuple{1, 2, 3.3}, std::array{3, 2, 1})
		== std::tuple{tuple_void, tuple_void, tuple_void}
	));

	assert
	((
		transform
		(
			overload
			{
				[](std::string, int){},
				std::plus<>{},
			},
			std::tuple{1, "2"s, "3"s},
			std::tuple{3, 2,    "1"s}
		)
		== std::tuple{4, tuple_void, "31"s}
	));

}

void TransformInPlace()
{

	{
		const char * ptr = "ptr";
		std::tuple t{1,ptr,3.0};
		transform([](auto&& x) { ++x; }, t);
		assert(( t == std::tuple{2, ptr + 1, 4.0} ));
	}

	{
		const char * ptr = "ptr";
		std::tuple t{1,ptr,3.0};
		assert(( transform([](auto&& x) { return x++; }, t) == std::tuple{1, ptr, 3.0} ));
		assert(( t == std::tuple{2, ptr + 1, 4.0} ));
	}

}

template <size_t I, size_t S>
constexpr iteration_state<I,std::make_index_sequence<S>> i_state{};

struct
{
	template <size_t Index, typename Range, typename... Values>
	auto operator()(iteration_state<Index,Range>, Values... v)
	{
		return (Range::size() - Index) * (v + ...);
	}
} sum_mul_sub_index;

void TransformIterationState()
{

	assert
	((
		transform([](auto i, auto, auto) { return i; },
			std::tuple{1, 2, 3.3}, std::array{3, 2, 1})
		== std::tuple{i_state<0,3>, i_state<1,3>, i_state<2,3>}
	));

	assert
	((
		transform([](auto i, auto, auto) { return i; },
			std::tuple{1, 2, 3.3, 4, 5}, std::array{3, 2, 1})
		== std::tuple{i_state<0,3>, i_state<1,3>, i_state<2,3>}
	));

	assert
	((
		transform([](auto i, auto x, auto y) { return i.index() + x + y; },
			std::tuple{1, 2, 3.3}, std::array{3, 2, 1})
		== std::tuple{4, 5, 6.3}
	));

	assert
	((
		transform(sum_mul_sub_index,
			std::tuple{1, 2, 3.3}, std::array{3, 2, 1, 0, -1, -2})
		== std::tuple{4*3,4*2,4.3*1}
	));

	assert
	((
		transform([](auto i, auto x, auto y) { return (i.range.size() - i.index()) * (x + y); },
			std::tuple{1, 2, 3.3}, std::array{3, 2, 1})
		== std::tuple{4*3,4*2,4.3*1}
	));

	assert
	((
		transform([](auto i, auto x, auto y)
			{
				if constexpr (i.index() % 2)
					return x + y;
				else
					return x - y;
			},
			std::tuple{1, 2, 3.3}, std::array{3, 2, 1})
		== std::tuple{-2, 4, 2.3}
	));

}

struct unlike_tuple {};
template <typename F>
std::string transform(F&&, const unlike_tuple&)
{return "Don't be too greedy!"; }

struct like_tuple
{
	int a;
	std::string b;

	bool operator==(const like_tuple& other) const
	{ return a == other.a && b == other.b; }
};

template <>
struct std::tuple_size<like_tuple> : public std::integral_constant<size_t, 2> {};

template <size_t I, typename T,
	std::enable_if_t<std::is_same_v<std::decay_t<T>,like_tuple>>* = nullptr>
decltype(auto) get(T&& t) noexcept
{
	static_assert(I < 2);
	if constexpr (I == 0)
	{
		return std::forward<T>(t).a;
	}
	else
	{
		return std::forward<T>(t).b;
	}
}

void TransformNonTuple()
{

	assert
	((
		from_tuple<like_tuple>(transform(
			std::plus<>{}, like_tuple{1,"1"s}, std::tuple{2,"2"s} ))
		==
		like_tuple{3, "12"s}
	));

	assert( transform([](){ return "Too greedy!"; }, unlike_tuple{}) == "Don't be too greedy!" );

}

void Dig()
{
	assert(( dig<0>(std::tuple{1,2,3}) == 1 ));
	assert(( dig<1>(std::tuple{1,2,3}) == 2 ));
	assert(( dig<2>(std::tuple{1,2,3}) == 3 ));

	assert(( dig<1,1>(std::tuple{std::tuple{1,2,3}, std::tuple{1,0,3}, std::tuple{1,2,3}}) == 0 ));

	assert(( dig<std::string>( std::pair{ std::pair{123, "ello"s}, 1.23} ) == "ello" ));
}

int main()
{
	ApplyFor();
	ApplyTo();
	CarCdr();
	TransformBasic();
	TransformCopyCount();
	TransformReturnVoid();
	TransformInPlace();
	TransformIterationState();
	TransformNonTuple();
	Dig();
	return 0;
}
